package com.gitee.hljdrl.wave;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

import com.gitee.hljdrl.wave.basis.WaveEvent;

public class WaveRelativeLayout extends RelativeLayout {

    protected WaveEvent mWaveEvent;


    public WaveRelativeLayout(Context context) {
        this(context, null);
    }

    public WaveRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WaveRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public WaveRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        //-----------------------------------------------------------
        mWaveEvent = new WaveDrawEvent();
        mWaveEvent.init(context, attrs);
        if (getVisibility() == View.VISIBLE) {
            mWaveEvent.startAnimation();
        }
    }


    public void startAnimation() {
        if (mWaveEvent != null) {
            if (!mWaveEvent.isRunning()) {
                mWaveEvent.startAnimation();
                invalidate();
            }
        }
    }

    public void stopAnimation() {
        if (mWaveEvent != null) {
            if (mWaveEvent.isRunning()) {
                mWaveEvent.stopAnimation();
            }
        }
    }

    public boolean isRunning() {
        if (mWaveEvent != null) {
            return mWaveEvent.isRunning();
        }
        return false;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //圆心位置
        //圆心位置
        if (mWaveEvent != null) {
            mWaveEvent.onSizeChanged(w, h, oldw, oldh);
        }
    }

    @Override
    public void draw(Canvas canvas) {
        if (mWaveEvent != null) {
            mWaveEvent.onDraw(canvas);
            if (mWaveEvent.isRunning()) {
                postInvalidateDelayed(10);
            }
        }
        super.draw(canvas);
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (mWaveEvent != null) {
            if (visibility == View.VISIBLE) {
                if (!mWaveEvent.isRunning()) {
                    startAnimation();
                }
            } else {
                if (mWaveEvent.isRunning()) {
                    stopAnimation();
                }
            }
        }
    }

}
